//
//  manageMyResumeEditJob.swift
//  DingDongZP
//
//  Created by 三秒文化 on 16/4/20.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

import UIKit

enum expectJobType {
    case Add
    case Edit
}

class manageMyResumeEditJob: LDBaseCustomizeVC {
    
    //
    var notifiParams:Int?
    var tableView:LDBaseTableView?
    var selectView:popActionSheetView?
    //获取cell列表
    var expectJobCategoryCell:baseMySettingCells?
    var expectJobIndustryCell:baseMySettingCells?
    var expectJobCityCell:baseMySettingCells?
    // 控制器
    var expectJobCategory:LDBase2ChoseJobDetailsVC?
    var expectJobIndustry:manageMyResumeExpectIndustry?
    
    
    //provience info
    var proviencParams = [String]()
    //
    var cityParams = [[[String:String]]]()
    //
    var pickV:LDBaseAddressPickerView?
    //选择的省份
    var provienceIndex = 0 {
        didSet{
            
            pickV?.pickView.reloadComponent(1)
        }
    }
    //城市所有数组
    var allCityData = [[String:AnyObject]]()
    //选择的城市row
    var cityIndex = 0
    //选择的省份中城市数组
    //选择的城市标题
    //期望工作空字典
    var addSendInfoDict = [String:AnyObject]() {
        didSet{
            
            debugPrint("期望工作字典-->",addSendInfoDict)
        }
    }
    
    var params:Dictionary<NSObject,AnyObject>? {
        didSet{
            model =  LDUserInfoExpectedJobModel.yy_modelWithDictionary(params!)
            
            let str1 = model?.expectjobcategory_name == nil ? "":model?.expectjobcategory_name
            let str2 = "\(model?.industrycount ?? "0")" + "个标签"
            let str3 = model?.expectcity_name == nil ? "":model?.expectcity_name
            let str4 = model?.expectsalary_text == nil ? "":model?.expectsalary_text
            requsetArr = [str1!,str2,str3!,str4!]
        }
    }
    
    var model:LDUserInfoExpectedJobModel? {
        didSet{
            tableView?.reloadData()
        }
    }
    
    var requsetArr = Array.init(count: 4, repeatedValue: "") {//"设计师","不限","杭州","100k-100k"]
        didSet{
            
            tableView?.reloadData()
        }
    }
    
    let eidtTitleArr = ["期望职位","期望行业","工作城市","薪资要求"]
    var selectExpSheetArr = [String]()
    
    var finishedBtn:UIButton?
    var deleteBtn:UIButton?
    
    var type:expectJobType? {
        didSet{
            creatBtn()
            view.layoutIfNeeded()
        }
    }
    
    override func viewDidLoad() {
        
        
        super.viewDidLoad()
        setDefaultContent()
        requestNetWork()
        setLocalNoti()
        
    }
//    override func viewWillAppear(animated: Bool) {
//        
//        navigationController?.navigationBar.barTintColor = LDGolbalColor.Green
//    }
    
    func requestNetWork() {
        //城市
        LDCheckPublicInfo.shareInstance.checkoutAllCityInfo { [weak self] (data) in
            self?.allCityData = data
            for item in data {
                let title = item["province_name"]! as! String
                self?.proviencParams.append(title)
                let cityArr = item["cities"] as! Array<Dictionary<String,String>>
                self?.cityParams.append(cityArr)
            }
        }
        //薪资要求
        LDCheckPublicInfo.shareInstance.checkoutAllSalary { [weak self] (data) in
            self?.selectExpSheetArr.removeAll()
            for item in data {
                let text = item["salary_text"] as! String
                self?.selectExpSheetArr.append(text)
            }
        }
    }
    
    //移除通知
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func setDefaultContent() {
        
        tableView = LDBaseTableView.init(frame: view.bounds, style: UITableViewStyle.Plain)
        tableView?.delegate = self
        tableView?.dataSource = self
        tableView?.scrollEnabled = false
        view.addSubview(tableView!)
        
    }
    //MARK: - 回调处理
    
    //MARK: - 设置期望工作
    
    //设置通知
    func setLocalNoti() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(manageMyResumeEditJob.getTapLabIndex(_:)), name: LDBaseTagsView().tagViewNotiName, object: nil)
        
    }
    
    //点击便签按钮事件
    func getTapLabIndex(noti:NSNotification) {
        
        let tagTitle = noti.userInfo!["control"] as! String
        
        if tagTitle == "LDBase2ChoseJobDetailsVC" {
            
            self.navigationController?.popViewControllerAnimated(false)
//            self.navigationController?.popViewControllerAnimated(false)
            
            let tag = noti.userInfo!["tag"] as? String
            let tag_id = noti.userInfo!["index"] as? String
            
            expectJobCategoryCell?.descLab?.text = tag
            addSendInfoDict["category_id"] = tag_id
        } else if tagTitle == "" {
            
        }
    }
    
    //MARK: - 设置薪资
    func getExpectSalary(tableView:UITableView,indexPath:NSIndexPath) {
        
        selectView = popActionSheetView()
        selectView!.selectSheetTextArr = selectExpSheetArr
        selectView?.btnH = 25
        selectView?.cancelBtnH = 30
        selectView?.showHeadView = true
        selectView?.headTitle = "薪资"
        
        selectView!.showview((navigationController?.view)!)
        let secCell = tableView.cellForRowAtIndexPath(indexPath) as! baseMySettingCells
        
        //选择index
        selectView?.selectOfRows({ [weak self] (title,index) in
            secCell.descLab?.text = title
            self?.addSendInfoDict["salary_id"] = "\(index)"
            })
    }
    
    
    func deleteExpectJob() {
        
        showLDAlertView("确认删除期望工作", sure: { [weak self] in
            
            LDUserInfoNet.sharedInstance.deleteExpectJob(expectjob_id: (self?.model?.expectjobid)!, success: {
                
                self?.sendNofiEditJob("期望工作删除成功")
                LDShowHUB.shareInstance.showSucc("期望工作删除成功")
                
            }) { (error) in
                LDShowHUB.shareInstance.showErr(error as! String)
            }
            
            self?.navigationController?.popViewControllerAnimated(true)
            
            }, cancel: nil)
        
    }
    //增加期望工作
    func addExpectJob() {
        
        LDNetWorkManager.sharedInstance.LoginPOSTSET(LDJobfinderAPI.create.expectedjob, parameters: addSendInfoDict, success: { [weak self] (value) in
            
            
            LDUserInfo.sharedInstance.updateUserInfo(nil, failure: nil)
            self?.sendNofiEditJob("期望工作增加成功")
            
            LDShowHUB.shareInstance.showSucc(value as! String)
            self?.navigationController?.popViewControllerAnimated(true)
        }) { (data, error) in
            
            LDShowHUB.shareInstance.showErr(data as! String)
        }
    }
    //修改期望工作
    func editExpectJob() {
        
        var dict = addSendInfoDict
        let expectjob_id = (model?.expectjobid)! as String
        dict["expectjob_id"] = expectjob_id
        
        debugPrint("expectjob_id--->",expectjob_id)
        LDNetWorkManager.sharedInstance.LoginPOSTSET(LDJobfinderAPI.edit.expectedjob, parameters: dict, success: { [weak self] (value) in
            
            LDUserInfo.sharedInstance.updateUserInfo(nil, failure: nil)
            
            self?.sendNofiEditJob("期望工作修改成功")
            LDShowHUB.shareInstance.showSucc(value as! String)
            self?.navigationController?.popViewControllerAnimated(true)
            
        }) { (data, error) in
            
            LDShowHUB.shareInstance.showErr(data as! String)
        }
    }
    //增加删除 增加 选中 通知
    func sendNofiEditJob(type:String) {
        
        NSNotificationCenter.defaultCenter().postNotificationName(NotiEidtExpJobName, object: self, userInfo: ["type":type])
    }
    //设置期望行业标签
    func setExpectJobKinds(indexPath:NSIndexPath,tableView:UITableView) {
    
        
        expectJobIndustryCell = tableView.cellForRowAtIndexPath(indexPath) as? baseMySettingCells
        expectJobIndustry = manageMyResumeExpectIndustry()
        
        var seltitlearr = [String]()
        
        if model?.industries != nil {
            
        
            for item in (model?.industries)! {
                let strid = item["industry_id"] as? String ?? "0"
//                let strtext = item["industry_name"] as? String ?? "NULL"
                
                let newid = Int(strid)! //- 1
                if  newid >= 0 {
                    seltitlearr.append(String.init(format: "%d", newid))
                }
            }
            expectJobIndustry!.preSelTitleID = seltitlearr
        }
        
        expectJobIndustry!.title = "期望行业"
        
        expectJobIndustry?.getInfoFromTabViewInfo({ [weak self] (params) in
            
            self?.expectJobIndustryCell?.descLab!.text = "\(params.count)个标签"
            var dicts = [String:AnyObject]()
            dicts["industriesIDs"] = params
            dicts["industriesNum"] = params.count
            
            self?.addSendInfoDict["industries"] = dicts.jsonString()
            
            })
        
        navigationController?.pushViewController(expectJobIndustry!, animated: true)
        
    }
}
extension manageMyResumeEditJob:UITableViewDelegate,UITableViewDataSource {
    // MARK: - Table view data source
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 4
    }
    
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCellWithIdentifier("cellsedit") as? baseMySettingCells
        if cell == nil {
            cell = baseMySettingCells.init(style: UITableViewCellStyle.Default, reuseIdentifier: "cellsedit")
        }
        
        cell?.titleLab?.text = eidtTitleArr[indexPath.row]
        cell?.descLab?.text = requsetArr[indexPath.row]
        return cell!
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        switch indexPath.row {
        case 0:
            
            expectJobCategoryCell = tableView.cellForRowAtIndexPath(indexPath) as? baseMySettingCells
            expectJobCategory = LDBase2ChoseJobDetailsVC()
            navigationController?.pushViewController(expectJobCategory!, animated: true)
            
        case 1:
            
            setExpectJobKinds(indexPath, tableView: tableView)
            
        case 2:
            
            pickV = LDBaseAddressPickerView()
            pickV!.pickView.delegate = self
            pickV!.pickView.dataSource = self
            pickV!.showview(self.view)
            expectJobCityCell = tableView.cellForRowAtIndexPath(indexPath) as? baseMySettingCells
            pickV!.sendStatus({ [weak self] (title) in
                if title == "确定" {
                    
                    let cityArr = self?.allCityData[(self?.provienceIndex)!]["cities"] as! Array<Dictionary<String,String>>
                    
                    if cityArr.count >= self?.cityIndex {
                        
                        let cityName = cityArr[(self?.cityIndex)!]["city_name"]
                        let cityID:String = cityArr[(self?.cityIndex)!]["city_id"]!
                        
                        self?.addSendInfoDict["city_id"] = cityID
                        self?.expectJobCityCell?.descLab?.text = cityName
                    }
                    
                }
                })
            
        case 3:
            getExpectSalary(tableView, indexPath: indexPath)
        default:
            break
        }
    }
    func setDefaultSelCityTag(row1:Int,row2:Int) {
        pickV?.pickView.selectRow(row2, inComponent: row1, animated: true)
        pickV?.pickView.reloadAllComponents()
    }
    
    func getCityIDFromTitle(title:String) {
        
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 60
    }
    
    func creatBtn() {
        
        finishedBtn = UIButton.setDetailsBtn("完成", picName: nil, btnBackColor: LDGolbalColor.Green, titleColor: LDFontColor.White)
        finishedBtn?.titleLabel?.font = LDFont.Font16
        finishedBtn?.hidden = true
        finishedBtn?.bk_whenTapped({ [weak self] in
            
            if self?.type == expectJobType.Edit {
                self?.editExpectJob()
            } else {
                self?.addExpectJob()
            }
            })
        
        deleteBtn = UIButton.setDetailsBtn("删除", picName: nil, btnBackColor: LDGolbalColor.Red, titleColor: LDFontColor.White)
        deleteBtn?.titleLabel?.font = LDFont.Font16
        deleteBtn?.hidden = true
        deleteBtn?.bk_whenTapped({ [weak self] in
            self?.deleteExpectJob()
            })
        
        view.addSubview(finishedBtn!)
        view.addSubview(deleteBtn!)
        
        
        if type == expectJobType.Add {
            title = "增加期望工作"
            finishedBtn?.hidden = false
            finishedBtn?.snp_makeConstraints(closure: { (make) in
                
                make.left.equalTo(LDMargin_H*2)
                make.right.equalTo(-LDMargin_H*2)
                make.height.equalTo(45)
                make.bottom.equalTo(-LDMargin_H*4)
            })
            
        } else if type == expectJobType.Edit {
            title = "编辑期望工作"
            finishedBtn?.hidden = false
            deleteBtn?.hidden = false
            
            finishedBtn?.snp_makeConstraints(closure: { (make) in
                
                make.left.equalTo(self.view.snp_centerX).offset(LDMargin_V)
                make.right.equalTo(-LDMargin_H*2)
                make.height.equalTo(45)
                make.bottom.equalTo(-LDMargin_H*4)
            })
            
            deleteBtn?.snp_makeConstraints(closure: { (make) in
                
                make.left.equalTo(LDMargin_H*2)
                make.right.equalTo(self.view.snp_centerX).offset(-LDMargin_V)
                make.height.equalTo(45)
                make.bottom.equalTo(-LDMargin_H*4)
            })
        }
    }
}
extension manageMyResumeEditJob:UIPickerViewDelegate,UIPickerViewDataSource {
    
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 2
    }
    
    
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 {
            return proviencParams.count
        } else {
            return cityParams[provienceIndex].count
        }
    }
    
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        
        if component == 0 {
            provienceIndex = row
            return proviencParams[row]
        } else {
            let cityArr = allCityData[provienceIndex]["cities"] as! Array<Dictionary<String,String>>
            let cityName:String = cityArr[row]["city_name"]!
            return cityName
        }
    }
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if component == 0 {
            provienceIndex = row
        } else {
            cityIndex = row
        }
    }
}




